import React from 'react';
import {Form} from 'antd';
import {isEmpty} from 'lodash';

// Form高阶组件，负责设置表单字段
@Form.create()
export default (option) => {
    if (typeof option === 'string') {
        option = {
            data: option
        };
    }
    const {
        data: dataName = 'data',
        title: formTitle = '',
        newData,
        oldData
    } = option;
    let getNewData = newData;
    if (typeof newData === 'object') {
        // TODO 为什么不能直接重设newData！！！
        getNewData = () => newData;
    }

    return Wrapped => class extends React.Component {
        componentWillReceiveProps(props) {
            const {[dataName]: data, form, title: title2 = ''} = props;
            if (data !== this.props[dataName]) {
                const isNew = isEmpty(data);
                let title;
                if (isNew) {
                    form.resetFields();
                    if (getNewData) {
                        form.setFieldsValue(getNewData());
                    }
                    title = `添加${formTitle}${title2}`;
                } else {
                    if (oldData) {
                        oldData(data);
                    }
                    form.setFieldsValue(data);
                    title = `修改${formTitle}${title2}`;
                }
                this.setState({title, isNew});
            }
        }

        render() {
            return <Wrapped {...this.props} {...this.state}/>;
        }
    };
};

/**
 * 常用的空校验规则
 * @param msg 提示信息
 */
export function emptyRule(msg) {
    return {
        required: true,
        whitespace: true,
        message: msg || '不能为空'
    };
}

/**
 * 生成数字输入框的验证规则
 * @param min 最小值
 * @param max 最大值
 * @return {*[]}
 */
export function numberRule(min, max) {
    const rules = [{
        pattern: /^([0-9]+)$/, message: '非法数字'
    }];
    if (typeof min === 'number' || typeof max === 'number') {
        if (!min) min = 0;
        if (!max) max = Infinity;
        rules.push({
            type: 'integer', min, max,
            transform: Number.parseInt,
            message: `必须介于${min}和${max}之间`
        });
    }
    return rules;
}
